package com.macrosolution.exdebito


import static org.springframework.http.HttpStatus.*

import org.codehaus.groovy.grails.web.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import grails.converters.JSON
import grails.transaction.Transactional
import grails.plugin.springsecurity.annotation.Secured;
import java.text.SimpleDateFormat;

/**
 * MessageController
 * A controller class handles incoming web requests and performs actions such as redirects, rendering views and so on.
 */
	@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_CC','ROLE_AVV','ROLE_C','ROLE_SC','ROLE_BCKOFF'])
@Transactional(readOnly = true)
class MessageController {
	
	static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
	
	def springSecurityService
	
	def index(Integer max) {
		params.max = Math.min(max ?: 10, 100)
		respond Message.list(params), model:[messageInstanceCount: Message.count()]
	}

	def list(Integer max) {
		params.max = Math.min(max ?: 10, 100)
		respond Message.list(params), model:[messageInstanceCount: Message.count()]
	}

	def show(Message messageInstance) {
		respond messageInstance
	}

	def create() {
		respond new Message(params)
	}

	@Transactional
	def save(Message messageInstance) {
		if (messageInstance == null) {
			notFound()
			return
		}

		if (messageInstance.hasErrors()) {
			respond messageInstance.errors, view:'create'
			return
		}

		messageInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.created.message', args: [message(code: 'messageInstance.label', default: 'Message'), messageInstance.id])
				redirect messageInstance
			}
			'*' { respond messageInstance, [status: CREATED] }
		}
	}

	def edit(Message messageInstance) {
		respond messageInstance
	}

	@Transactional
	def update(Message messageInstance) {
		if (messageInstance == null) {
			notFound()
			return
		}

		if (messageInstance.hasErrors()) {
			respond messageInstance.errors, view:'edit'
			return
		}

		messageInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.updated.message', args: [message(code: 'Message.label', default: 'Message'), messageInstance.id])
				redirect messageInstance
			}
			'*'{ respond messageInstance, [status: OK] }
		}
	}

	@Transactional
	def delete(Message messageInstance) {

		if (messageInstance == null) {
			notFound()
			return
		}

		messageInstance.delete flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.deleted.message', args: [message(code: 'Message.label', default: 'Message'), messageInstance.id])
				redirect action:"index", method:"GET"
			}
			'*'{ render status: NO_CONTENT }
		}
	}

	protected void notFound() {
		request.withFormat {
			form {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'messageInstance.label', default: 'Message'), params.id])
				redirect action: "index", method: "GET"
			}
			'*'{ render status: NOT_FOUND }
		}
	}
	
	
	def calendarMessage(){
		
		def user = springSecurityService.currentUser
		
//		def listMessage= Message.findAllByUserID(user.id)
//		def messageMap =[]
//		JSONObject jMap = new JSONObject()
//
//		JsonObject f = new JsonObject()
//
//		listMessage.eachWithIndex {item,counter->
//
//			messageMap.push("id":item.id.toString(),"title":item.message,"className":["event", "bg-color-greenLight"])
//			messageMap["id"]=item.id
//			messageMap["title"]=item.message
			
//			def d =	 messageMap.get(counter)
//			println d
//			jMap.put(counter, d)
			
			
//		}
		
//		Gson d = new Gson()
//		def er = d.toJson(messageMap)
//		println er
//			render(view:"/message/calendarMessage", model:[eventsList : er])
			render(view:"/home/index")
			
	}
	def renderJsonMessage(){
		
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		def listMessage = Message.findAll()
		listMessage.each {Message m ->
			
			def evList = m.eventUser
			evList.each {EventUser ev->				
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}
		def messageMap =[]		
		
		JSONObject jMap = new JSONObject()		
		JsonObject f = new JsonObject()
		
		lm.toList().eachWithIndex {item,counter->
			
			String eventClass=item.eventColor + " "+ "fa" + " " + item.eventIcon
			messageMap.push("id":item.id.toString(),"title":item.eventTitle,start:item.expire,end:item.dateEnd,"className":["event", eventClass])
//			messageMap["id"]=item.id
//			messageMap["title"]=item.message
			
//			def d =	 messageMap.get(counter)
//			println d
//			jMap.put(counter, d)		
		}		
		Gson d = new Gson()
		def er = d.toJson(messageMap)		
		render er		
	}

		
	def status(){
		def totMsg = 0
		// numero messaggi FAKE
		def numMsg = 3
		// numero task FAKE
		def numTask = 4
		//numero Eventi
		def numEvent = 0
		def toDay = new Date();
		toDay.time=toDay.time-86400000
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		Set<Message> listMessage = Message.findAllByExpireGreaterThan(toDay,[sort: "expire", order: "asc"])
		listMessage.each {Message m ->
			def evList = m.eventUser
			evList.each {EventUser ev->
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}
		numEvent = lm.size
		totMsg = numEvent
		if(!session.total_message){
			render '<i class="fa fa-group"></i> <b class="badge bg-color-red bounceIn animated"> '+totMsg+' </b> ';			
		} else {
			if(session.total_message != totMsg){
				session.total_message = totMsg
				render '<i class="fa fa-group"></i> <b class="badge bg-color-red bounceIn animated"> '+totMsg+' </b> ';
			} else {
				render '<i class="fa fa-group"></i> <b class="badge bounceIn animated"> 0 </b> ';
			}	
		}	
	}
	
	def status_change(){
		def totMsg = 0
		// numero messaggi FAKE
		def numMsg = 3
		// numero task FAKE
		def numTask = 4
		//numero Eventi
		def numEvent = 0
		def toDay = new Date();
		toDay.time=toDay.time-86400000
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		Set<Message> listMessage = Message.findAllByExpireGreaterThan(toDay,[sort: "expire", order: "asc"])
		listMessage.each {Message m ->
			def evList = m.eventUser
			evList.each {EventUser ev->
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}
		numEvent = lm.size
		totMsg = numEvent
		if(!session.total_message){
			session.total_message=totMsg
		}
		render 'ok';
	}

	def eventNum(){
		def eventNum = 0
		def numEvent = 0
		def toDay = new Date();
		toDay.time=toDay.time-86400000
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		Set<Message> listMessage = Message.findAllByExpireGreaterThan(toDay,[sort: "expire", order: "asc"])
		listMessage.each {Message m ->	
			def evList = m.eventUser
			evList.each {EventUser ev->
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}
		eventNum = lm.size
		
		render eventNum;
	}
	
	def get_latest_tasks(){
		
		def out='<script type="text/javascript">'
		
		
		out+='$(document).ready(function(){$(\'.todo .checkbox > input[type="checkbox"]\').click(function() {var $this = $(this).parent().parent().parent();if ($(this).prop(\'checked\')) {$this.addClass("complete");$(this).parent().hide();$this.slideUp(500, function() {$this.clone().prependTo("#sortable3").effect("highlight", {}, 800);$this.remove();countTasks();});} else {}});$("#sortable1, #sortable2").sortable({handle : \'.handle\',connectWith : ".todo",update : countTasks}).disableSelection();});'

		// count tasks
		out+='function countTasks(){$(\'.todo-group-title\').each(function() {var $this = $(this);$this.find(".num-of-tasks").text($this.next().find("li").size());});}</script>'
		out+='<div role="content"><div class="jarviswidget-editbox"><div><label>Titolo:</label><input type="text"></div></div>'
			out+= '<div class="no-margin widget-body no-padding smart-form"><h5 class="todo-group-title"><i class="fa fa-warning"></i> Tasks Critici (<small class="num-of-tasks">1</small>)</h5>'
		
			out+='<ul id="sortable1" class="todo ui-sortable"><li><span class="handle"> <label class="checkbox"><input type="checkbox" name="checkbox-inline"><i></i> </label> </span><p style="height:auto;"><strong>Ticket #0043</strong> - Richiedere la privacy dell\'utente D.. [<a href="javascript:void(0);" class="font-xs">Piu Informazioni</a>] <span class="text-muted">Senza la privacy non posso confermarti e farti andare avanti con la pratica </span><span class="date">15/02/2015</span></p></li></ul>'
			
			out+='<h5 class="todo-group-title"><i class="fa fa-exclamation"></i> Tasks Importanti (<small class="num-of-tasks">3</small>)</h5>'
			out+='<ul id="sortable2" class="todo ui-sortable">'
			out+='<li>	<span class="handle"> <label class="checkbox">			<input type="checkbox" name="checkbox-inline">			<i></i> </label> </span>	<p style="height:auto;">		<strong>Ticket #1347</strong> - Inviata gia due volte la mail per la conferma <small>(risolto blocco)</small> [<a href="javascript:void(0);" class="font-xs">More Details</a>] <span class="date"></span>17/02/2015</p></li>'
			out+='<li>	<span class="handle"> <label class="checkbox">			<input type="checkbox" name="checkbox-inline">			<i></i> </label> </span>	<p style="height:auto;">		<strong>Ticket #1314</strong> - Contattare il supporto operativo per chiarimenti <a href="javascript:void(0);" class="font-xs">#6134</a><small>(codice di riferimento)</small>		<span class="date">18/01/2015</span>	</p></li>'
			out+='<li>	<span class="handle"> <label class="checkbox">			<input type="checkbox" name="checkbox-inline">			<i></i> </label> </span>	<p style="height:auto;">		<strong>Ticket #17643</strong> - Confermare il numero di telefono del cliente 043 [<a href="javascript:void(0);" class="font-xs">Piu Informazioni</a>] <span class="text-muted">Controllare vista l\'inesistenza del numero e i dati non conformi</span>		<span class="date">28/12/2014</span>	</p></li>'
			out+='</ul>'
			out+='<h5 class="todo-group-title"><i class="fa fa-check"></i> Tasks Comletati (<small class="num-of-tasks">1</small>)</h5>'
			out+='<ul id="sortable3" class="todo">'
			out+='<li class="complete">	<span class="handle" style="display:none"> <label class="checkbox state-disabled">			<input type="checkbox" name="checkbox-inline" checked="checked" disabled="disabled">			<i></i> </label> </span>	<p style="height:auto;">		<strong>Ticket #0053</strong> - Inserire tutti i documenti per lAnomalia Bancaria[<a href="javascript:void(0);" class="font-xs">Piu Informazioni</a>] <span class="text-muted">Inserire i doc e andare avanti con il sovraindebitamento</span>		<span class="date">Jan 1, 2014</span>	</p></li>'
			out+='</ul>'
			out+='</div>'
			out+='</div>'
			render out;
	}
	
	def get_latest_events(){
		def toDay = new Date();
		toDay.time=toDay.time-86400000
		
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		Set<Message> listMessage = Message.findAllByExpireGreaterThan(toDay,[sort: "expire", order: "asc"])
		listMessage.each {Message m ->
			
			def evList = m.eventUser
			evList.each {EventUser ev->			
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}
		def totalOut='<div class="ajax-notifications custom-scroll" style="opacity: 1;"><ul class="notification-body">'
		for(Message event:lm){
			def out=''
			out+='<li>'
			out+='<span class="padding-10 unread">'
			out+='<em class="badge padding-5 no-border-radius bg-color-purple txt-color-white pull-left margin-right-5">'
			out+='<i class="fa fa-calendar fa-fw fa-2x"></i>'
			out+='</em>'
			out+='<span>'
			out+='<a href="#" onClick="openDetailMessagePP('+event.id+')" class="display-normal"><strong>Evento</strong></a>: '+event.eventTitle+''
			out+='<br>'
			def sdf = new SimpleDateFormat("dd/MM/yyy")
			def timef = new SimpleDateFormat("H:mm")
			out+='<strong>Data: '+sdf.format(event.expire)+'  ('+timef.format(event.expire)+')</strong><br>'
			def msg =''
			if(event?.message){
				 msg = event?.message
				 if(msg.size()>25) {
					  msg = msg[0..24]
				 }
			}
			out+='<span class="pull-right font-xs text-muted"><i>'+msg+'...</i></span>'
			out+='</span>'
			out+='</span>'
			out+='</li>'
			totalOut+=out
		}
		totalOut+='</ul>'
		totalOut+='</div>'
			
		render totalOut;	
	}
	
	def get_latest_messages(){
		
		def out='<div class="ajax-notifications custom-scroll" style="opacity: 1;">'
		out+='<ul class="notification-body">'
		out+='<li>'
		out+='<span class="unread">'
		out+='<a href="javascript:void(0);" class="msg">'
		out+='<img src="/images/avatar/4.png" alt="" class="air air-top-left margin-top-5" width="40" height="40">'
		out+='<span class="from">Luigi Ursino <i class="icon-paperclip"></i></span>'
		out+='<time>2 minuti fa</time>'
		out+='<span class="subject">Riunione corso</span>'
		out+='<span class="msg-body">Ciao, ricorda di portare la pennetta USB. </span>'
		out+='</a>'
		out+='</span>'
		out+='</li>'
		out+='<li>'
		out+='<span>'
		out+='<a href="javascript:void(0);" class="msg">'
		out+='<img src="/images/avatar/1.png" alt="" class="air air-top-left margin-top-5" width="40" height="40">'
		out+='<span class="from">Daniela Ursino</span>'
		out+='<time>Mercoledi 11 Febbraio</time>'
		out+='<span class="subject">Mail personale</span>'
		out+='<span class="msg-body">La mia mail � daniela@me.com</span>'
		out+='</a>'
		out+='</span>'
		out+='</li>'
		out+='<li>'
		out+='<span>'
		out+='<a href="javascript:void(0);" class="msg">'
		out+='<img src="/images/avatar/5.png" alt="" class="air air-top-left margin-top-5" width="40" height="40">'
		out+='<span class="from">Angela Brescia</span>'
		out+='<time>Mercoledi 4 Febbraio</time>'
		out+='<span class="subject">Documenti Sovraindebitamento</span>'
		out+='<span class="msg-body"> In allegato i vari documenti necessari per il calcolo del sovraindebitamento. Vi sono chiari?</span>'
		out+='</a>'
		out+='</span>'
		out+='</li>'
		out+='</ul>'
		out+='</div>'
		
		render out
		
		
	}
	
	
	
	def messageDetail(){

		def user = springSecurityService.currentUser
		def eventInstance = Message.findById(params.id)
		def userId = user.id
		render (template:'/message/showDetailMessage' ,model:[eventInstance:eventInstance,userId:userId]) 

		
	}
	
	@Transactional
	def create_event(){
		
		if(params.eventTitle==null || params.eventTitle==""){
			
			response.status=401
			render "Errore:inserire il titolo!"
			return
			
		}
		if(params.dStart==null || params.dStart=="" || params.startHour==null || params.startHour=="" ||params.dEnd==null || params.dEnd=="" || params.endHour==null||params.endHour==""){
			
			response.status=401
			render "Errore:le date e gli orari non possono essere vuoti!"
			return
			
		}
		def dateTimeStart=params.dStart + " " +params.startHour
		def dateTimeEnd=params.dEnd + " " +params.endHour
		SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		Date start = dt.parse(dateTimeStart)
		
		Date end = dt.parse(dateTimeEnd);
		
		Calendar calendarStart = Calendar.getInstance()
		Calendar calendarEnd = Calendar.getInstance()
		calendarStart.setTime(start)
		calendarEnd.setTime(end)
		
		
		def annoInizio = calendarStart.get(Calendar.YEAR)
		def meseInizio = calendarStart.get(Calendar.MONTH)
		def giornoInizio = calendarStart.get(Calendar.DAY_OF_MONTH)
		def oraInizio = calendarStart.get(Calendar.HOUR_OF_DAY)
		def minutiInizio = calendarStart.get(Calendar.MINUTE)
		
		def annoFine = calendarEnd.get(Calendar.YEAR)
		def meseFine = calendarEnd.get(Calendar.MONTH)
		def giornoFine = calendarEnd.get(Calendar.DAY_OF_MONTH)
		def oraFine = calendarEnd.get(Calendar.HOUR_OF_DAY)
		def minutiFine = calendarEnd.get(Calendar.MINUTE)
		def hisec = (oraInizio*60)+minutiInizio
		def hfsec = (oraFine*60)+minutiFine
		def difference = hfsec-hisec
		println difference
		if(annoInizio==annoFine && meseInizio==meseFine && giornoInizio==giornoFine){
			
			if(oraInizio>oraFine){
				
				response.status=401
				render "Errore:ricontrollare orari"
				return
				
			}
			if(oraInizio==oraFine){
				
				if(minutiInizio>minutiFine){
					
					response.status=401
					render "Errore:ricontrollare orari"
					return
				
				}
				
			}
			if(difference<60){
				response.status=401
				render "Errore:un evento deve durare almeno	un'ora"
				return
				
			}
			
		}
		
		
		
		
//		Date start = new Date(dateTimeStart).parse("d/M/yyyy H:m", dateTimeStart)
//		Date end= new Date(dateTimeEnd).parse("d/M/yyyy H:m", dateTimeEnd)
		
		
		
		params.expire = start
		params.dateEnd = end
		def usrList = params.eventUserId
		if(!usrList){
			
			
			response.status=401
			render "L'evento deve essere asseganto almeno ad un utente"
			return
			
		}
		def listEv = params.eventUserId
		Message message_instance = new Message(params)
		List<EventUser> listEu = new ArrayList<EventUser>()
		listEv.each{evId->
			
			EventUser ev = new EventUser()
			ev.setUserId(new Long(evId))
			ev.setEsito("");
			listEu.add(ev)
		}
		message_instance.eventUser=new ArrayList<EventUser>()
		listEu.each{EventUser evu->
			
			evu.save(flush:true)
			message_instance.eventUser.add(evu)
			
			
			
		}
		
		
		if(message_instance){
			if(message_instance.save(flush:true)){
				
				render "Evento Creato correttamente"
				
			}else{
				
				response.status=401
				render "ops:qualcosa non va riprovare pi� tardi"
			}
			
		}
		else{
			
			response.status=401
			render "Errore:evento non creato,riprovare in seguito"
		}
		
	}
	
	@Transactional
	def delete_event(){
		
		Message messageInstance = Message.findById(params.event_id)
		if(messageInstance){
			List<EventUser> eu = messageInstance.eventUser.toList()
			for(EventUser e:eu){
				messageInstance.removeFromEventUser(e)
				messageInstance.save(flush:true)
				e.delete(flush:true)
			}
			messageInstance.delete(flush:true)
			render "Evento Cancellato"
			
		}else{
		
			response.status=401
			render "Cancellazione non riuscita riporvare in seguito"
		
		}
		
	}
	
	def loadAppenings(){
		def toDay = new Date();
		toDay.time=toDay.time-86400000
		
		def user = springSecurityService.currentUser
		List<Message> lm = new ArrayList<Message>()
		Set<Message> listMessage = Message.findAllByExpireGreaterThan(toDay,[sort: "expire", order: "asc", max:5])
		listMessage.each {Message m ->			
			def evList = m.eventUser
			evList.each {EventUser ev->
				if(ev.userId==user.id){
					lm.add(m)
				}
			}
		}	
		
		render template:'appenings', model:[events:lm]		
	}
	
	def shadduspup(){
		
		//utente collegato
		User lgUsr = springSecurityService.currentUser
		
		render (template:"/message/addMessagePuP",model:[usr:lgUsr])
	}
	
	def get_current_leave(){
		User lgUsr = springSecurityService.currentUser
		User usr = User.get(params.id)
		def checked = 'checked="checked"'
		Role usrRole = UserRole.findByUser(usr).role
		def results = '<li  id="user_'+params.id+'"><span id="span_'+params.id+'"><i class="fa fa-lg fa-user">'+' '+'<input type="checkbox"  class="parentCheckBox" '+checked+' disabled="disabled" name="eventUserId" value="'+usr.id+'"></i>'
		results += '<b> '+	usrRole.label
		results += ' - ' + usr.name + '</b></span></li>'
		
		render results
		
		
	}
	
	def get_role_name(){
		
		User usr = User.get(params.id)
		Role usrRole = UserRole.findByUser(usr).role
		
		render JSON.parse("{'text':' "+usrRole.label+" - "+usr.surname+" "+(usr.name).substring(0,1).toUpperCase()+"."+"','id':"+params.id+"}") as JSON
	}
	
	def get_father(){
		User lgUsr = springSecurityService.currentUser
		
		User usr = User.get(params.id)
		def disabled = ""
		def checked = ""
		
		Role usrRole = UserRole.findByUser(usr).role
		
		
		def results = '<li id="user_'+params.id+'"><span id="span_'+params.id+'"><i class="fa fa-lg fa-user">'+' '+'<input type="checkbox" '+disabled+' '+checked+' name="eventUserId" value="'+usr.id+'"></i>'
		results += '-'+	usrRole.label
		results += ' - ' + usr.name + '</span></li>'
		
		render results
		
		
	}
	
}